package com.way.filemanager.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.way.filemanager.FileManagerAppFrame;
import com.way.filemanager.R;
import com.way.filemanager.providers.FilelistManager;
import com.way.filemanager.providers.FilelistManager.ChangeStatusCb;
import com.way.filemanager.util.CommonFunc;
import com.way.filemanager.util.CommonIdDef;

import java.io.File;

public class CategoryFragment extends Fragment implements activity2frag_if,ChangeStatusCb{
    private static final String TAG = "CategoryFragment";
    private static final String ARGUMENT_NUMBER = "num";
    int mNum;
    Activity mActivity;
    private View mMainView;

    ViewGroup mSubTypesView;
    ViewGroup mMainTypesView;
    CategorySubtypeView mCategorySubtypeView;
    int mViewTypes;
    FilelistManager mFileListManager;
    CategoryListAdpter mImageAdpter;
    Runnable mRefreash;
    static long refreshTimeStamp;
    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static CategoryFragment newInstance(int num) {
        CategoryFragment f = new CategoryFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt(ARGUMENT_NUMBER, num);
        f.setArguments(args);

        return f;
    }

    Handler mHandler = new LocalHandler();
    @SuppressLint("HandlerLeak")
    public class LocalHandler extends Handler {
        @Override
            public void handleMessage(Message msg) {
            switch(msg.what) {
                case CommonIdDef.CATEGORY_MESSAGE_ID_BACK:
                    switchToMainTypes();
                    break;
            default:
                break;
            }
        }
    }
    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt(ARGUMENT_NUMBER) : 1;
        mActivity = getActivity();
        //BugID:99830:fix FragmentList size is 0 bug after change language
        ((FileManagerAppFrame)mActivity).setFragmentMap(0, this);
    }
    @Override
    public void onStop()
    {
        super.onStop();
    }
    @Override
    public void onStart()
    {
        super.onStart();
    }
    @Override
    public void onResume()
    {
        super.onResume();

        IntentFilter iFilter = new IntentFilter(Intent.ACTION_MEDIA_EJECT);
        iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        iFilter.addAction(CommonFunc.BroadcastActionScan);
        iFilter.addDataScheme("file");
        mActivity.registerReceiver(mUnmountReceiver, iFilter);

        //bug110920
        //if(mCategorySubtypeView != null)
        //    mCategorySubtypeView.BackToUpLevel();

    }
    @Override
    public void onPause()
    {
        mActivity.unregisterReceiver(mUnmountReceiver);
        Log.v(TAG, TAG+"--onPause");
        super.onPause();
    }
    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.category_main, container, false);
        mMainView = v;
        mMainView.setId(CommonIdDef.FRAGMENT_CATEGORY_ID);

        mMainTypesView = (ViewGroup)mMainView.findViewById(R.id.category_main_id);
        initFileRefresh();
        initMainTypesView();
        refreshTimeStamp = System.currentTimeMillis();
        mRefreash = new Runnable()
        {
            @Override
            public void run() {
                if(mFileListManager.isScaning())
                {
                    long temp = System.currentTimeMillis();
                    if((temp - refreshTimeStamp)>200)
                    {
                        refreshFileItem();
                    }
                    refreshTimeStamp = temp;
                    mHandler.postDelayed(mRefreash, 20);
                }
                else
                {
                    refreshFileItem();
                    //Scan finish
                }
            }
        };
        mHandler.postDelayed(mRefreash, 20);
        //progressRefresh();
        return v;
    }

    @Override
    public boolean fragOnKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        boolean ret=false;
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(mViewTypes != CommonIdDef.CATEGORY_MAIN_VIEW)
            {
                BackToUpLevel();
                return true;
            }
        }
        return ret;
    }

    @Override
    public boolean exit() {
        // TODO Auto-generated method stub
        mHandler.removeCallbacks(mRefreash);
        mHandler.removeCallbacks(mFileListManagerRun);
        return true;
    }

    void initMainTypesView()
    {
        mMainTypesView.setVisibility(View.VISIBLE);
        mViewTypes = CommonIdDef.CATEGORY_MAIN_VIEW;
        GridView gridview = (GridView) mMainView.findViewById(R.id.Category_grid);
        mImageAdpter = new CategoryListAdpter(mActivity, mFileListManager);
        gridview.setAdapter(mImageAdpter);
        gridview.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                Log.v(TAG, "setOnItemClickListener" + view.getId());
                switchToSubTypesView(view.getId());
            }
            }
        );
        mMainView.setOnKeyListener(new OnKeyListener(){
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.v(TAG, "setOnKeyListener:" + keyCode +" action:"+ event.getAction());
                return false;
            }

        });
    }

    private void ensureSubTypeView()
    {
        if(null == mSubTypesView)
        {
            ViewStub subTypesViewStub = (ViewStub)getView().findViewById(R.id.category_subtypes_id);
            mSubTypesView = (ViewGroup)subTypesViewStub.inflate();
        }
    }

    void switchToSubTypesView(int types)
    {
        if(mFileListManager.isScaning())
        {
            Toast t = Toast.makeText(mActivity, R.string.CategoryLoading_warning, Toast.LENGTH_SHORT);
            t.show();
            return;
        }

        if(mCategorySubtypeView == null)
        {
            mCategorySubtypeView = new CategorySubtypeView(mActivity, mFileListManager, mHandler);
        }
        else
        {
            mCategorySubtypeView.uninit();
        }

        ensureSubTypeView();
        mViewTypes = types;
        mCategorySubtypeView.init(mSubTypesView, types);
        String EnterMode = null;
        switch(types)
        {
            case CommonIdDef.CATEGORY_ITEM_ID_PICTURE:
                EnterMode = CommonFunc.Category_Image;
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_MUSIC:
                EnterMode = CommonFunc.Category_Music;
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_VIDEO:
                EnterMode = CommonFunc.Category_Video;
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_PACKAGE:
                EnterMode = CommonFunc.Category_Apk;
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_TEXT:
                EnterMode = CommonFunc.Category_Text;
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_ZIP:
                EnterMode = CommonFunc.Category_Zip;
                break;
        }
        CommonFunc.TA_EnterMode(EnterMode);
        mMainTypesView.setVisibility(View.INVISIBLE);
        mSubTypesView.setVisibility(View.VISIBLE);
    }
    void BackToUpLevel()
    {
        if(!mCategorySubtypeView.BackToUpLevel())
        {
            switchToMainTypes();
        }

    }
    void switchToMainTypes()
    {
        mMainTypesView.setVisibility(View.VISIBLE);
        mSubTypesView.setVisibility(View.INVISIBLE);
        mViewTypes = CommonIdDef.CATEGORY_MAIN_VIEW;
        refreshFileItem();
    }
    Runnable mFileListManagerRun;
    void initFileRefresh()
    {
        mFileListManager = new FilelistManager(mActivity);
        mFileListManager.StartRun();
        /*mFileListManagerRun = new Runnable()
        {
            @Override
            public void run() {
                mFileListManager.StartRun();
            }
        };

        mHandler.postDelayed(mFileListManagerRun, 30);*/
        mFileListManager.setMainViewCb(this);
    }

    void refreshFileItem()
    {
        if((mViewTypes == CommonIdDef.CATEGORY_MAIN_VIEW)&&(mMainTypesView !=null))
        {
            if(mFileListManager!= null)
            {
                progressRefresh();
                mImageAdpter.notifyDataSetChanged();
            }
        }

    }
    void progressRefresh()
    {
        final long totalSize = mFileListManager.GetTotleSDSize();
        if(totalSize > 0 )
        {
            TextView storage_unuse_memory;
            storage_unuse_memory = (TextView)mMainView.findViewById(R.id.storage_unuse_memory_id);
            String TxtMeminfo = mActivity.getString(R.string.capacity_all)
                                 + CommonFunc.FormetFileSize(totalSize) +" "
                                 + mActivity.getString(R.string.capacity_avail)
                                 + CommonFunc.FormetFileSize(mFileListManager.GetTotleAvailSize());

            storage_unuse_memory.setText(TxtMeminfo);

            TextView progress_other = (TextView)mMainView.findViewById(R.id.capacity_progress_other);
            TextView progress_image = (TextView)mMainView.findViewById(R.id.capacity_progress_image);
            TextView progress_video = (TextView)mMainView.findViewById(R.id.capacity_progress_video);
            TextView progress_audio = (TextView)mMainView.findViewById(R.id.capacity_progress_audio);
            TextView progress_document = (TextView)mMainView.findViewById(R.id.capacity_progress_document);
            TextView progress_apk = (TextView)mMainView.findViewById(R.id.capacity_progress_apk);
            TextView progress_archive = (TextView)mMainView.findViewById(R.id.capacity_progress_archive);

            TextView memory_Sum_other = (TextView)mMainView.findViewById(R.id.capacity_text_other);
            TextView memory_Sum_image = (TextView)mMainView.findViewById(R.id.capacity_text_picture);
            TextView memory_Sum_video = (TextView)mMainView.findViewById(R.id.capacity_text_video);
            TextView memory_Sum_audio = (TextView)mMainView.findViewById(R.id.capacity_text_music);
            TextView memory_Sum_document = (TextView)mMainView.findViewById(R.id.capacity_text_text);
            TextView memory_Sum_apk = (TextView)mMainView.findViewById(R.id.capacity_text_apk);
            TextView memory_Sum_archive = (TextView)mMainView.findViewById(R.id.capacity_text_zip);

            setSubtypeProgressAndSize(progress_image, memory_Sum_image, CommonIdDef.CATEGORY_ITEM_ID_PICTURE
                    , R.string.CategoryItemPic);
            setSubtypeProgressAndSize(progress_video, memory_Sum_video, CommonIdDef.CATEGORY_ITEM_ID_VIDEO
                    , R.string.CategoryItemVideo);
            setSubtypeProgressAndSize(progress_audio, memory_Sum_audio, CommonIdDef.CATEGORY_ITEM_ID_MUSIC
                    , R.string.CategoryItemMusic);
            setSubtypeProgressAndSize(progress_document, memory_Sum_document, CommonIdDef.CATEGORY_ITEM_ID_TEXT
                    , R.string.CategoryItemText);
            setSubtypeProgressAndSize(progress_apk, memory_Sum_apk, CommonIdDef.CATEGORY_ITEM_ID_PACKAGE
                    , R.string.CategoryItemApk);
            setSubtypeProgressAndSize(progress_archive, memory_Sum_archive, CommonIdDef.CATEGORY_ITEM_ID_ZIP
                    , R.string.CategoryItemZip);
            setOtherTypeProgressAndSize(progress_other, memory_Sum_other);
        }
    }

    private void setSubtypeProgressAndSize(TextView progressView, TextView capacityView, int subType
            , int subTypeFotmatString)
    {
        final long totalSize = mFileListManager.GetTotleSDSize();

        String txtSpace = " ";
        View capacityBar = mMainView.findViewById(R.id.capacity_bar);
        long totalWidth = capacityBar.getWidth();
        long subTypeSize = mFileListManager.GetTypeSize(subType);
        long w = totalWidth * subTypeSize / totalSize;
        progressView.setWidth((int) w);
        capacityView.setText(mActivity.getResources().getText(subTypeFotmatString)
                + txtSpace + CommonFunc.FormetFileSize(subTypeSize));
    }

    private void setOtherTypeProgressAndSize(TextView progressView, TextView capacityView)
    {
        boolean isScanFinish = !mFileListManager.isScaning();
        long other = 0;
        final long totalSize = mFileListManager.GetTotleSDSize();
        if(isScanFinish) {
            other = (mFileListManager.GetTotleSDSize() - mFileListManager.GetTotleAvailSize())
                 - mFileListManager.GetTypeSize(CommonIdDef.CATEGORY_ITEM_ID_PICTURE)
                 - mFileListManager.GetTypeSize(CommonIdDef.CATEGORY_ITEM_ID_VIDEO)
                 - mFileListManager.GetTypeSize(CommonIdDef.CATEGORY_ITEM_ID_MUSIC)
                 - mFileListManager.GetTypeSize(CommonIdDef.CATEGORY_ITEM_ID_TEXT)
                 - mFileListManager.GetTypeSize(CommonIdDef.CATEGORY_ITEM_ID_PACKAGE)
                 - mFileListManager.GetTypeSize(CommonIdDef.CATEGORY_ITEM_ID_ZIP);
         }

        String txtSpace = " ";
        LinearLayout capacity_bar = (LinearLayout) mMainView.findViewById(R.id.capacity_bar);
        long totalWidth = capacity_bar.getWidth();
        final long w = totalWidth * other / totalSize;
        progressView.setWidth((int) w);
        capacityView.setText(mActivity.getResources().getText(R.string.CategoryItemNone)
                + txtSpace + CommonFunc.FormetFileSize(other));
    }

    @Override
    public boolean setLoginStatus(boolean status) {
        return false;
    }
    @Override
    public boolean judgeUpload() {
        return false;
    }
    private BroadcastReceiver mUnmountReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
                mFileListManager.syncDir(null, true, null);
            } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
                    ||action.equals(CommonFunc.BroadcastActionScan)) {
                Uri Uripath = intent.getData();
                File temp = new File(Uripath.getPath());
                String Path = temp.getPath();
                boolean deleteSelf = intent.getBooleanExtra(CommonIdDef.DELETE_BY_FILEMANAGER, false);
                if(!deleteSelf)
                    mFileListManager.syncDir(Path, true, null);
            }
            /// @}
        }
    };
    @Override
    public boolean setMobileFlag() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void FileListChanged(int type) {
        // TODO Auto-generated method stub
        mHandler.post(new Runnable()
        {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                refreshFileItem();
            }

        });

    }
}